//
//  EditMailViewController.swift
//  ZhiTing
//
//  Created by zy on 2022/6/7.
//

import UIKit
import SwiftUI


class EditMailViewController: BaseViewController {

    var emailType = EmailCaptchaType.email_change_bind
    
    lazy var descLabel = Label().then{
        $0.font = .font(size: 14, type: .medium)
        $0.textColor = .custom(.black_3f4663)
        $0.textAlignment = .center
    }
    
    private lazy var mailTextField = TitleTextField(title: "新邮箱".localizedString, placeHolder: "请输入邮箱地址".localizedString, isSecure: false).then {
        $0.limitCount = 100
    }

    private lazy var doneButton = LoadingButton(title: "下一步".localizedString)
    
    private lazy var mailSelectedView = EditMailSelectedView().then{
        $0.backgroundColor = .custom(.white_ffffff)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if emailType == .email_change_bind {
            self.title = "更换邮箱".localizedString
            descLabel.text = "当前邮箱：" + UserManager.shared.currentUser.email
        }else{
            self.title = "解绑邮箱".localizedString
            descLabel.text = "请选择一种验证方式进行验证"
        }
    }
    
    override func setupViews() {
        view.addSubview(descLabel)
        view.addSubview(mailTextField)
        view.addSubview(mailSelectedView)
        view.addSubview(doneButton)
        
        doneButton.clickCallBack = { [weak self] _ in
            guard let self = self else { return }
            self.doneButtonClick()
        }

    }
    
    override func setupConstraints() {
        descLabel.snp.makeConstraints {
            $0.top.equalTo(Screen.k_nav_height + 10)
            $0.left.right.equalToSuperview()
        }
        
        mailTextField.snp.makeConstraints {
            $0.top.equalTo(descLabel.snp.bottom).offset(ZTScaleValue(56))
            $0.left.equalTo(ZTScaleValue(30))
            $0.right.equalTo(-ZTScaleValue(30))
        }
        
        if emailType == .email_change_bind {
            mailTextField.isHidden = false
            mailSelectedView.snp.makeConstraints {
                $0.top.equalTo(mailTextField.snp.bottom).offset(ZTScaleValue(15))
                $0.left.equalTo(ZTScaleValue(30))
                $0.right.equalTo(-ZTScaleValue(30))
            }
        }else{
            mailTextField.isHidden = true
            mailSelectedView.snp.makeConstraints {
                $0.top.equalTo(descLabel.snp.bottom).offset(ZTScaleValue(56))
                $0.left.equalTo(ZTScaleValue(30))
                $0.right.equalTo(-ZTScaleValue(30))
            }
        }
        
        doneButton.snp.makeConstraints {
            $0.bottom.equalTo(-160 * Screen.screenRatio)
            $0.centerX.equalToSuperview()
            $0.left.equalToSuperview().offset(ZTScaleValue(30))
            $0.right.equalToSuperview().offset(-ZTScaleValue(30))
            $0.height.equalTo(50)
        }
        
    }

    override func setupSubscriptions() {
        mailTextField.textPublisher
            .map { $0 != "" }
            .sink { [weak self] (isEnable) in
                guard let self = self else { return }
                if self.emailType == .email_change_bind {
                    self.doneButton.isEnabled = isEnable
                    self.doneButton.alpha = isEnable ? 1 : 0.5
//                    self.doneButton.setIsEnable(isEnable)
                }else{
                    self.doneButton.alpha = 1
//                    self.doneButton.setIsEnable(true)
                }
                
            }
            .store(in: &cancellables)
    
    }
}

extension EditMailViewController {
    private func doneButtonClick() {
        
        if emailType == .email_change_bind {
            if !(mailTextField.text.count > 0) {
                showToast(string: "新邮箱地址不能为空".localizedString)
                return
            }
            
            //校验邮箱格式是否正确
            if !validateEmail(email: mailTextField.text) {
                showToast(string: "请输入正确邮箱地址".localizedString)
                return
            }
            //检测邮箱是否被绑定过
            ApiServiceManager.shared.checkEmailIsBind(email: mailTextField.text) {[weak self] response in
                guard let self = self else {return}
                if response.is_bind {
                    self.showToast(string: "邮箱已被绑定")
                }else{
                    let vc = MailVerificationViewController()
                    vc.emailType = self.emailType
                    guard let isChooesPhone = self.mailSelectedView.isChooesPhone else {
                        self.showToast(string: "请选择验证方式")
                        return
                    }
                    vc.captchaType = isChooesPhone ? .phone : .email
                    vc.newEmail = self.mailTextField.text
                    self.navigationController?.pushViewController(vc, animated: true)

                }
            } failureCallback: {[weak self] code, err in
                guard let self = self else {return}

                self.showToast(string: err)
            }
        }else{
            let vc = MailVerificationViewController()
            vc.emailType = self.emailType
            guard let isChooesPhone = self.mailSelectedView.isChooesPhone else {
                self.showToast(string: "请选择验证方式")
                return
            }
            vc.captchaType = isChooesPhone ? .phone : .email
            vc.newEmail = self.mailTextField.text
            self.navigationController?.pushViewController(vc, animated: true)
        }
        



 
    }
    
    //校验邮箱格式
    private func validateEmail(email: String) -> Bool{
        let mailPattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest: NSPredicate = NSPredicate(format: "SELF MATCHES %@", mailPattern)
        return emailTest.evaluate(with: email)
    }
}
